<template>
  <button class="icon" @click="buy">
    <i class="cuifont icon_user_plus"></i>
  </button>
</template>

<script>
import { PayContext } from '@/components/storybook/s-pay/pay-context'
import { get, cloneDeep } from 'lodash'

export default {
  name: 'aLaCartePay',
  props: ['detail'],
  data () {
    return {}
  },
  computed: {
    product () {
      return cloneDeep(PayContext.product) || {}
    }
  },
  methods: {
    async buy () {
      const { subscriptionId, appId } = this.detail
      //
      PayContext.subscriptionId = subscriptionId
      PayContext.appId = appId
      PayContext.infoModal = false
      await this.open()
      PayContext.payType = this.detail.type
      PayContext.payModal = 'pay'
    },
    async open () {
      try {
        this.loading = true
        const { subscriptionId } = PayContext || {}
        await this.getProduct()
        let events = []
        if (subscriptionId) {
          events.push(this.getSub())
        }
        if (this.product.type === 2) {
          events.push(this.getIntegrationLimit(), this.getRules(this.product.appId))
        }
        await Promise.all(events)
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    async getProduct () {
      const { getAppInfoApi } = this.$interface.reports
      const { appId } = PayContext || {}
      const params = {
        id: appId
      }

      const { data: response } = await getAppInfoApi(params)
      if (response.code !== 0) {
        throw response.msg
      }

      PayContext.product = response.data

      return PayContext.product
    },
    async getIntegrationLimit () {
      const { getReportDataInfo } = this.$interface.reports
      const params = {
        gadgetId: '76c35523-5a44-42b6-875d-6b00215349e7',
        gadgettype: 'gridgadget',
        type: 'widget',
        code: 'TEAMS'
      }
      let { data: response } = await getReportDataInfo(params)

      if (response.code !== 0) {
        throw get(response, 'msg', '')
      }

      this.integrationLimit = response.data || []
    },
    async getRules (ids) {
      const { rules } = this.$interface.pay

      const params = {
        ids
      }
      let { data: response } = await rules(params)
      if (response.code !== 0) {
        throw get(response, 'msg', '')
      }

      this.rules = response.data || []
    },
    async getSub () {
      const { payInfo } = this.$interface.pay
      const { appId, subscriptionId } = PayContext || {}
      const params = {
        appId,
        subscriptionId
      }
      let { data: response } = await payInfo(params)
      if (response.code !== 0) {
        throw get(response, 'msg', '')
      }

      PayContext.subscription = response.data

      return PayContext.subscription
    }
  }
}
</script>

<style scoped>

</style>
